package login_controller

import (
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"

	web_constants "app/app_src/framework/constant/web"
	"app/app_src/framework/i18n"
	common_util "app/app_src/framework/util/common"
	web_util "app/app_src/framework/util/web"
	context_path_util "app/app_src/framework/util/web/context_path"
	login_constants "app/app_src/modules/login/constant"
	login_service "app/app_src/modules/login/service"
)

// 登录页面
func Login(ctx *gin.Context) {
	web_util.OkHTML(ctx, "login/login", nil)
}

// 登出
func Logout(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Delete(login_constants.SESSION_KEY_CURRENT_SUBJECT)
	session.Save()

	// 登出后重定向到登录页面
	ctx.Redirect(http.StatusFound, context_path_util.WithContextPath(web_constants.URL_LOGIN_PAGE))
}

// 登录处理API
func DoLogin(ctx *gin.Context) {
	params := web_util.GetJsonParam(ctx)
	userName := common_util.EmptyStringIfNil(params.GetAsString("username"))
	password := common_util.EmptyStringIfNil(params.GetAsString("password"))

	// 检查认证信息
	subject, ok := login_service.CheckLogin(userName, password)

	if ok {
		// 保存登录信息
		login_service.SaveLoginSuccessInfo(ctx, subject)
		web_util.OkResult(ctx, nil)
	} else {
		web_util.BizErrorResult(ctx, login_constants.LOGIN_FAILED, i18n.T("账号或密码错误！"))
	}
}
